import React, { Component } from 'react'
import styles from './index.module.scss'
import { Flex, Toast } from 'antd-mobile'
import SearchBar from '../../components/SearchBar'
import { getCurrentCity } from '../../utils/city'
import Filter from '../../components/Filter'
import { getHouseLit } from '../../api/houselist'
import {
  AutoSizer,
  List,
  InfiniteLoader,
  WindowScroller
} from 'react-virtualized'
import HouseItem from '../../components/HouseItem'
import Affix from '../../components/Affix'

export default class HouseList extends Component {
  constructor () {
    super()

    this.state = {
      cityName: '深圳',
      count: 0, // 加载的总条数
      houseList: null // 房源列表
    }
  }

  // 过滤条件
  filter = {}

  async componentDidMount () {
    const { label, value } = await getCurrentCity()

    this.setState({
      cityName: label
    })

    // 查询房源列表
    this.id = value

    // 不带条件查询第一页
    this.getHouseListData()
  }

  getHouseListData = async () => {
    Toast.loading('数据加载中...', 0)
    const res = await getHouseLit({ cityId: this.id, data: this.filter })
    Toast.hide()

    if (res.data.body.count > 0) {
      Toast.info(`共查询到 ${res.data.body.count} 套房源`)
    }

    this.setState({
      count: res.data.body.count,
      houseList: res.data.body.list
    })
  }

  // 当筛选条件改变之后，发送请求
  onConditionChange = data => {
    // 处理区域或是地铁
    // areaKey area、subway
    const areaKey = data.area[0]
    if (data.area.length >= 2 && data.area[1] !== 'null') {
      this.filter[areaKey] =
        data.area[2] === 'null' ? data.area[1] : data.area[2]
    } else {
      this.filter[areaKey] = null
    }

    // 处理mode
    if (data.mode.length > 0 && data.mode[0] !== 'null') {
      this.filter.rentType = data.mode[0]
    } else {
      this.filter.rentType = null
    }

    // 处理price
    if (data.price.length > 0 && data.price[0] !== 'null') {
      this.filter.price = data.price[0]
    } else {
      this.filter.price = null
    }

    // 处理more
    if (data.more.length > 0) {
      this.filter.more = data.more.join(',')
    } else {
      this.filter.more = null
    }

    this.getHouseListData()
  }

  // 渲染每一行
  rowRenderer = ({ key, index, style }) => {
    const data = this.state.houseList[index]

    if (!data) {
      return (
        <div style={style}>
          <div className={styles.loading}>加载中...</div>
        </div>
      )
    }

    return <HouseItem key={key} style={style} {...data} />
  }

  // 判断某一行是否加载完毕
  isRowLoaded = ({ index }) => {
    return !!this.state.houseList[index]
  }

  // 加载更多
  loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise(async (resolve, reject) => {
      const res = await getHouseLit({
        cityId: this.id,
        data: this.filter,
        start: startIndex,
        end: stopIndex
      })

      this.setState(
        {
          count: res.data.body.count,
          houseList: [...this.state.houseList, ...res.data.body.list]
        },
        () => {
          resolve()
        }
      )
    })
  }

  render () {
    const { count, houseList } = this.state

    return (
      <div className={styles.root}>
        <Flex className={styles.listHeader}>
          <i
            onClick={() => this.props.history.goBack()}
            className='iconfont icon-back'
          />
          <SearchBar
            className={styles.mySearchBar}
            cityName={this.state.cityName}
          />
        </Flex>
        <Affix>
          {/* 过滤组件 */}
          <Filter onConditionChange={this.onConditionChange} />
        </Affix>
        {houseList && (
          <AutoSizer>
            {({ width }) => (
              <InfiniteLoader
                isRowLoaded={this.isRowLoaded}
                loadMoreRows={this.loadMoreRows}
                rowCount={count}
                minimumBatchSize={20}
              >
                {({ onRowsRendered, registerChild }) => (
                  <WindowScroller>
                    {({ height, isScrolling, onChildScroll, scrollTop }) => (
                      <List
                        autoHeight // 跟随window滚动的时候一定要加上
                        isScrolling={isScrolling}
                        onScroll={onChildScroll}
                        scrollTop={scrollTop}
                        height={height}
                        width={width}
                        onRowsRendered={onRowsRendered}
                        ref={registerChild}
                        rowCount={count} // 如果是分页加载，必须是总条数
                        rowHeight={120}
                        rowRenderer={this.rowRenderer}
                      />
                    )}
                  </WindowScroller>
                )}
              </InfiniteLoader>
            )}
          </AutoSizer>
        )}
      </div>
    )
  }
}
